const PENDING = 'pengding'
const RESOLVED = "resolved"
const REJECTED = 'rejected'

function MyPormise (fn)  {
    const self = this
    self.state = PENDING
    self.value = null

    self.resolveCallback = []
    self.rejectCallback = []

    const resolve = (value) => {
        if (self.state === PENDING) {
            self.state = RESOLVED
            self.value = value
            self.resolveCallback.forEach(cb => cb(self.value))
        }
    }
    const reject = (value) => {
        if (self.state === PENDING) {
            self.state = REJECTED
            self.value = value
            self.resolveCallback.forEach(cb => cb(self.value))
        }
    }

    try {
        fn(resolve, reject)
    } catch (e) {
        reject(e)
    }
}

MyPormise.prototype.then = function (onFullFilled, onRejected) {
    const self = this
    onFullFilled = typeof onFullFilled === 'function' ? onFullFilled : v => v
    onRejected = typeof onRejected === 'function' ? onRejected : r => {
        throw r
    }

    if (self.state === PENDING) {
        self.resolveCallback.push(onFullFilled)
        self.rejectCallback.push(onRejected)
    }

    if(self.state === RESOLVED) {
        onFullFilled(self.value)
    }
    if(self.state === REJECTED) {
        onRejected(self.value)
    }
}

new MyPormise((resolve, reject) => {
    setTimeout(() => {
        resolve(123)
    }, 1e3);
}).then(res => {
    console.log(res, 'haha')
})

